package com.urbanski.clipboard.client.action;

import java.io.IOException;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.common.message.TestMessage;
import com.urbanski.util.logging.LoggingUtil;

public class TestActionHandler extends ClientActionHandler
{
	private static final Logger LOGGER = Logger.getLogger(TestActionHandler.class);
	
	private String host;
	private int port = 0;
	
	public TestActionHandler(String[] tokens)
	{
		super(ClientCommand.TEST, tokens);
	}

	@Override
	public void execute()
	{
		LOGGER.trace("Entering TestActionHandler.execute");

		processArgs();
		
		if (host != null && port > 0)
		{
			ServerConnection serverConnection = new ServerConnection(host, port);
			try
			{
				serverConnection.connect();
				LoggingUtil.logAndPrintInfo(LOGGER, "Successfully connected to " + host + ':' + port);
				serverConnection.sendMessage(new TestMessage());
				serverConnection.close();
			}
			catch (UnknownHostException e)
			{
				LoggingUtil.logAndPrintDebug(LOGGER, "Unknown host: " + host + ':' + port);
			}
			catch (IOException e)
			{
				LoggingUtil.logAndPrintDebug(LOGGER, "Connection to " + host + " refused on port " + port);
			}
		}
		
		LOGGER.trace("Exiting TestActionHandler.execute");
	}
	
	private void processArgs()
	{
		if (tokens.length != 3)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Invalid number of arguments for test command");
			return;
		}
		
		host = tokens[1];
		try
		{
			port = Integer.parseInt(tokens[2]);
		}
		catch (NumberFormatException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Invalid port: " + tokens[2]);
		}
	}
}
